module game
{
	/**pop消除的规则，单独提出来，目的是方便扩展 */
	export class PopRules
	{

		/**返回值，可消除的pop的数组编号 */
		public static check(pops:Array<Array<BasePop>>):Array<egret.Point>
		{
			let result = [];

			//1.以中心pop开始检测，读取横线、竖线是否能超过三个同颜色的
			let len = pops.length;
			for(let i = 0;i < len;i++)
			{
				let len1 = pops[i].length;
				for(let j = 0;j < len1;j++)
				{
					let pop = pops[i][j];
					if(pop)
					{
						if(pop.isBlank){continue;}
						
						//1.检测横向
						let h_pre = this.check_pre(i,j,pops,true);
						let h_next = this.chekc_next(i,j,pops,true);
						if(h_pre && h_next)
						{
							//横向可以消除
							result.push(egret.Point.create(i - 1,j));
							result.push(egret.Point.create(i,j));
							result.push(egret.Point.create(i + 1,j));
							let n = 1;
							//继续检测下一个
							while(this.chekc_next(i + n,j,pops,true))
							{
								result.push(egret.Point.create(i + n + 1,j));
								n++;
							}
						}
						
						//2.检测竖向
						let v_pre = this.check_pre(i,j,pops,false);
						let v_next = this.chekc_next(i,j,pops,false);
						if(v_pre && v_next)
						{
							//竖向可以消除
							//继续检测下一个
							result.push(egret.Point.create(i,j - 1));
							result.push(egret.Point.create(i,j));
							result.push(egret.Point.create(i,j + 1));
							let n = 1;
							//继续检测下一个
							while(this.chekc_next(i,j + n,pops,false))
							{
								result.push(egret.Point.create(i,j + n + 1));
								n++;
							}
						}
					}
				}
			}

			result = this.removeRepeat(result);
			return result;
		}

		/**数组去重 */
		private static removeRepeat(arr:Array<egret.Point>):Array<egret.Point>
		{
			let obj = {};
			let result:Array<egret.Point> = [];
			for(let i = arr.length - 1;i >= 0;i--)
			{
				let pt = arr[i];
				obj[pt.x + "" + pt.y] = pt;
			}
			
			for(let key in obj)
			{
				result.push(obj[key]);
			}

			return result;
		}

		private static chekc_next(i:number,j:number,pops:Array<Array<BasePop>>,flag:boolean):boolean
		{
			let result = false;
			let pop = pops[i][j];
			let next:BasePop;
			if(flag)//横
			{
				if(pops.length > i+1)
				{
					next = pops[i + 1][j];
				}
			}
			else//竖
			{
				if(pops[i].length > j+1)
				{
					next = pops[i][j + 1];
				}
			}

			if(next)
			{
				result = pop.type == next.type;
			}

			return result;
		}

		private static check_pre(i:number,j:number,pops:Array<Array<BasePop>>,flag:boolean):boolean
		{
			let result = false;
			let pop = pops[i][j];
			let pre:BasePop;

			if(flag)//横
			{
				if(i - 1 >= 0)
				{
					pre = pops[i - 1][j];
				}
			}
			else//竖
			{
				if(j - 1 >= 0)
				{
					pre = pops[i][j - 1];
				}
			}

			if(pre)
			{
				result = pop.type == pre.type;
			}

			return result;
		}
	}
}